package com.markedquilt.mvcframework.servlet;
/*
 * PackageName: com.markedquilt.mvcframework
 * ClassName:   LgDispatcherServlet
 * Author:   coke
 * Date:     Created in 2020/10/21 20:45
 * Description:
 * History:
 * <author>        <time>             <version>          <desc>
 * 作者姓名         修改时间            版本号              描述
 * coke           2020/10/21 20:45     1.0
 */

import com.markedquilt.mvcframework.anntations.*;
import com.markedquilt.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ZhangKe
 * @Project mvc-demo
 * @Description
 * @date 2020/10/21 20:45.
 */
public class LgDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();    //缓存扫描到的类的全限定类名

    private Map<String,Object> ioc = new HashMap<String,Object>();

//    private Map<String,Method> handlerMapping = new HashMap<>();    //存储url和method之间的映射关系

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        String contextConfigLocations = config.getInitParameter("contextConfigLocations");
        doLoadConfig(contextConfigLocations);

        //2.扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));

        //3.初始化Bean（实现IOC容器，基于注解）
        doInstance();

        //4.实现依赖注入
        doAutowired();

        //5.初始化SpringMVC相关组件，这里构造一个HandlerMapping处理器映射器，将配置好的url和Method建立映射
        initHandlerMapping();
        System.out.println("SpringMVC初始化完成...");

        //等待请求进入，处理请求
    }

    //这里构造一个HandlerMapping处理器映射器
    /**
     * 构造一个HandlerMapping处理器映射器
     * 最关键的环节
     * 目的：将url和method建立关联
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()){return;}
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取ioc中当前遍历的class类型
            Class<?> aClass = entry.getValue().getClass();
            //如果不是Controller，跳出循环
            if (!aClass.isAnnotationPresent(LagouController.class)){continue;}

            String baseUrl= "";
            if (aClass.isAnnotationPresent(LagouRequestMapping.class)){
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value();
            }

            //获取方法
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                //  方法没有标识LagouRequestMapping，就不处理
                if (!method.isAnnotationPresent(LagouRequestMapping.class)){continue;}

                //  如果标识，就处理
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;

                //把method所有信息及url封装为一个Handler
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));

                //计算方法的位置信息
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];

                    if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        //如果是request或者response对象，那么参数名称写HttpServletRequest或者HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(),i);
                    }
                }
                //如果方法上带了@MySecurity注解，取值，加入白名单
                if (aClass.isAnnotationPresent(MySecurity.class)){
                    //如果controller带了@MySecurity
                    String[] controllerWhiteName = aClass.getAnnotation(MySecurity.class).value();
                    handler.getWhiteList().addAll(Arrays.asList(controllerWhiteName));
                }
                if (method.isAnnotationPresent(MySecurity.class)){
                    MySecurity mySecurity = method.getAnnotation(MySecurity.class);
                    String[] whiteName = mySecurity.value();
                    if (whiteName.length>0)
                        handler.getWhiteList().addAll(Arrays.asList(whiteName));
                }
                //建立url和method之间的映射关系（map缓存起来）
                handlerMapping.add(handler);
            }
        }
    }

    // 实现依赖注入
    private void doAutowired() {
        if (ioc.isEmpty()){return;}

        //有对象，再进行依赖注入处理

        //遍历ioc中的所有对象，查看对象中的字段，是否有@LagouAutowired，如果有需要维护依赖注入关系
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取bean对象中的字段信息
            for (Field declaredField : entry.getValue().getClass().getDeclaredFields()) {
                if (!declaredField.isAnnotationPresent(LagouAutowired.class)){
                    continue;
                }
                //有该注解
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                String beanName = annotation.value();   //需要注入的beanName
                if ("".equals(beanName.trim())){
                    //没有配置具体的beanName，那就需要根据当前字段类型注入（接口注入）
                    beanName = declaredField.getType().getSimpleName();
                }
                //开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //ioc容器，基于classNames缓存的类的全限定类名，以及反射技术，完成对象的创建和管理
    private void doInstance(){
        if (classNames.size() == 0) return;
        try{
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i);

                //反射
                Class<?> aClass = Class.forName(className);

                //区分controller，service
                if (aClass.isAnnotationPresent(LagouController.class)){
                    //这里controller直接取类名首字母小写，保存到ioc
                    String simpleName = aClass.getSimpleName();
                    String lowerSimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerSimpleName,o);
                }
                else if (aClass.isAnnotationPresent(LagouService.class)){
                    //获取注解value
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    String beanName = annotation.value();
                    //制定了ID，就以指定的为准
                    if (!beanName.trim().equals(""))
                        ioc.put(beanName,aClass.newInstance());
                    else{
                        //没有指定
                        beanName = lowerFirst(aClass.getSimpleName());
                        Object o = aClass.newInstance();
                        ioc.put(beanName,o);
                    }

                    //Service一般有接口，面向接口开发，此时再以接口名为id，放一份到ioc，便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        //以接口的全限定名作为id放入
                        ioc.put(anInterface.getSimpleName(),aClass.newInstance());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public String lowerFirst(String str){
        char[] chars = str.toCharArray();
        if (chars[0]<='Z' && chars[0]>='A')
            chars[0] += 32;
        return String.valueOf(chars);
    }

    //扫描类
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        if (files!=null)
            for (File file : files) {
                if (file.isDirectory()){
                    //递归
                    doScan(scanPackage + "." + file.getName());
                }else if (file.getName().endsWith(".class")){
                    String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                    classNames.add(className);
                }
            }
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocations) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocations);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求,根据url，找到对应Method方法，进行调用
        //获取uri
//        String requestURI = req.getRequestURI();
//        Method method = handlerMapping.get(requestURI);
        //反射调用，需要传入对象和参数，此处无法完成调用，没有把对象缓存起来，也没有参数
//        method.invoke();

        Handler handler = getHandler(req);
        if (handler == null){
            resp.getWriter().write("404 not found");
            return;
        }

        //参数绑定
        //获取所有参数类型数组，这个数组长度就是我们最后要传入的args的数组长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        //根据上述数组长度创建一个新数组（参数数组，是要传入反射调用的）
        Object[] paramValues = new Object[parameterTypes.length];

        //以下就是为了向参数数组中塞值，而且还的保证参数顺序和方法中形参顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();

        //遍历request中所有参数（除request\response之外的普通参数）
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            String value = StringUtils.join(param.getValue(), ",");

            //如果参数和方法中的参数匹配上了，填充数据
            if (!handler.getParamIndexMapping().containsKey(param.getKey())){continue;}

            //包含该参数，找到他的索引位置，对应参数值放入paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());//索引位置
            paramValues[index] = value; //把前端传过来的参数填充到对应位置去
        }

        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paramValues[requestIndex] =req;

        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paramValues[responseIndex] =resp;

        String userName = req.getParameter("name");
        if (userName !=null){
            for (String s : handler.getWhiteList()) {
                if (s.equals(userName)){
                    //有权访问，则跳出循环
                    System.out.println("当前用户有权访问");
                    //最终调用handler的method属性
                    try {
                        handler.getMethod().invoke(handler.getController(),paramValues);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    return;
                }
            }
            //无权访问，则结束访问
            System.out.println("当前用户无权访问");
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()){return null;}

        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }
}
